var recognition = new SpeechRecognition();
recognition.lang = "zh-CN";
recognition.continuous = true;
recognition.interimResults = true;

var txt = "";
var test = "";
var recognizing = false;
var finalTranscript = "";
var start = Date.now();
var pauseTime = 15000; // 最长停顿时间为15秒
recognition.onresult = function(event) {
  var result = "";
  for (var i = event.resultIndex; i < event.results.length; i++) {
    if (event.results[i].isFinal) {
      result += event.results[i][0].transcript;
      test +=result;
    } else {
      result += event.results[i][0].transcript;
    }
  }
  var now = Date.now();
  if (now - start >= pauseTime) { // 判断是否超过最长停顿时间
    finalTranscript += test; // 将之前识别的内容添加到最终结果中
    test = ""; // 清空test变量
  }
  start = Date.now();
  txt = result;
  console.log(txt);
  document.getElementById("inputTxt").value = test;
};

recognition.addEventListener("result", (event) => {
  var transcript = event.results[0][0].transcript;
  console.log("识别结果：", transcript);
  finalTranscript = transcript; // 修复第一个bug
});

recognition.addEventListener("end", () => {
  console.log("最终识别结果：", finalTranscript);
  txt = test;
  test = "";
  document.getElementById("inputTxt").innerHTML = txt;
  recognizing = false;
  document.getElementById("startButton").innerHTML = "开始";
  var res;
        window.shunxu++;
        res={
          userTxt:txt,
          text: "文章"+"-"+window.选择文章+"-"+window.shunxu,
          action:actions
        };
        console.log(txt);
        txt=""
        ws_send(res);
});

document.getElementById("startButton").addEventListener("click", function() {
  if (!recognizing) {
    if (!recognition.running) {
      recognition.start();
    }
    recognizing = true;
    document.getElementById("startButton").innerHTML = "停止";
  } else {
    recognition.stop();
  }
});
